<?php
// +-------------------------------------------------------------------------------
// | DingZone [ A Rapid Development Framework For Dingtalk ]
// +-------------------------------------------------------------------------------
// | SQL运行器 v1.0
// |
// | Copyright (c) 2014-2018 http://www.heimalanshi.com All rights reserved.
// | Author : Jie
// | Date : 2018-08-09
// +-------------------------------------------------------------------------------

namespace db;


use common\Random;
use PhpMyAdmin\SqlParser\Utils\Formatter;
use think\Db;

class SqlRunner {

    /**
     * 运行sql文件
     *
     * @param $path
     * @return bool|int
     */
    public static function runFile($path) {
        if (!file_exists($path)) {
            return false;
        }
        $content = file_get_contents($path);
        if (empty($content)) {
            return false;
        }

        $lineEnding = "\r\n##_SQL_SPECIAL_LINE_ENDING_400_893_0087_" . Random::get() . "_##\r\n";
        $indentation = "\r\n##_SQL_INDENTATION_400_893_0087_" . Random::get() . "_##\r\n";
        Formatter::$SHORT_CLAUSES = [];
        $content = Formatter::format($content, [
            'line_ending' => $lineEnding,
            'indentation' => $indentation,
            'remove_comments' => true,
            'parts_newline' => false,
            'clause_newline' => false,
            'indent_parts' => true
        ]);
        $content = str_replace($lineEnding . $indentation, " ", $content);
        $lines = explode($lineEnding, $content);

        Db::startTrans();
        $sql = "";
        foreach ($lines as $line) {
            $sql .= "\n" . $line;
            if (endsWith($line, ";")) {
                Db::execute($sql);
                $sql = "";
            }
        }
        if (!empty($sql)) {
            Db::execute($sql);
        }
        Db::commit();
    }
}